<template>
  <div class="global-container">
    <div class="global-header">
      <el-image style="width: 100px; height: 100px" :src="require('@/assets/header_images/current.png')"></el-image>
      <div class="title">
        云原生管理
        <div class="title-content">
          提供云原生服务的生命周期管理能力，支持服务启停、状态监控、yaml编辑、升级回滚等功能。
        </div>
      </div>
    </div>
    <div class="searchDiv1">
      <div class="searchDiv global-operate">
        <span class="keyword">关键词：</span>
        <el-input v-model="searchInput" placeholder="请输入服务名称、部署名称、部署描述检索" clearable class="inputStyle" style="width: 26%"
          prefix-icon="el-icon-search" @input="filterServiceInstanceList" />
        <div style="float: right">
          <el-button type="primary" size="small" class="el-button-primary-style" @click="startCloudNative">启 动
          </el-button>
          <el-button type="primary" size="small" class="el-button-primary-style" style="margin-right: 10px"
            @click="stopCloudNative">停 止
          </el-button>
          <!-- <el-button type="primary" size="small" @click="deleteSelectInstances">删 除</el-button>-->
          <el-popconfirm title="确认删除实例？" @confirm="deleteCloudNative">
            <el-button type="primary" size="small" slot="reference" class="el-button-primary-style"
              style="margin-right: 10px" :disabled="selectRowList.length === 0">
              删 除
            </el-button>
          </el-popconfirm>
        </div>
        <!-- <el-button type="primary" size="small" style="background-color: #304156; border-color: #304156;" @click="filterServiceInstanceList">查 询</el-button> -->
        <!--        <div style="float: right">-->
        <!--          <el-button-->
        <!--            type="primary"-->
        <!--            size="small"-->
        <!--            @click="startSelectInstances"-->
        <!--            class="el-button-primary-style"-->
        <!--          >启 动-->
        <!--          </el-button>-->
        <!--          <el-button-->
        <!--            type="primary"-->
        <!--            size="small"-->
        <!--            @click="stopSelectInstances"-->
        <!--            class="el-button-primary-style"-->
        <!--            style="margin-right: 10px;"-->
        <!--          >停 止-->
        <!--          </el-button>-->
        <!--          &lt;!&ndash; <el-button type="primary" size="small" @click="deleteSelectInstances">删 除</el-button>&ndash;&gt;-->
        <!--          <el-popconfirm-->
        <!--            title="确认删除服务实例？"-->
        <!--            @confirm="deleteSelectInstances"-->
        <!--          >-->
        <!--            <el-button-->
        <!--              type="primary"-->
        <!--              size="small"-->
        <!--              slot="reference"-->
        <!--              class="el-button-primary-style"-->
        <!--              style="margin-right: 10px;"-->
        <!--            >-->
        <!--              删 除-->
        <!--            </el-button>-->
        <!--          </el-popconfirm>-->
        <!--        </div>-->
      </div>
    </div>
    <div>
      <div class="servicePackageList">
        <div style="height: 65vh">
          <el-table :data="tableData" style="width: 100%" ref="multipleTable" @selection-change="tableSelectionChange">
            <!--            :cell-style="{ textAlign: 'left', paddingLeft: '30px' }"-->
            <!--            :header-cell-style="{ textAlign: 'left', paddingLeft: '30px' }"-->
            <el-table-column type="selection" align="center"></el-table-column>
            <el-table-column label="部署名称">
              <template slot-scope="scope">
                <el-tooltip effect="dark" :content="scope.row.yamlDeployName" placement="bottom-start"
                  popper-class="tooltipClass" :disabled="isShowTooltip">
                  <div class="descSpan" style="text-align: left" @mouseover="onMouseOver($event)">
                    {{ scope.row.yamlDeployName }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="名称" width="200">
              <template slot-scope="scope">
                <el-tooltip effect="dark" :content="scope.row.yamlZhname" placement="bottom-start"
                  popper-class="tooltipClass" :disabled="isShowTooltip">
                  <div class="descSpan" @mouseover="onMouseOver($event)">
                    {{ scope.row.yamlZhname }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="服务标识" width="200">
              <template slot-scope="scope">
                <el-tooltip effect="dark" :content="scope.row.yamlInterface" placement="bottom-start"
                  popper-class="tooltipClass" :disabled="isShowTooltip">
                  <div class="descSpan" @mouseover="onMouseOver($event)">
                    {{ scope.row.yamlInterface }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="服务描述">
              <template slot-scope="scope">
                <el-tooltip effect="dark" :content="scope.row.yamlDescription" placement="bottom"
                  popper-class="tooltipClass" :disabled="isShowTooltip">
                  <div class="descSpan" @mouseover="onMouseOver($event)">
                    {{ scope.row.yamlDescription }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column prop="yamlVersion" label="服务版本" width="110">
            </el-table-column>
            <el-table-column prop="yamlDeployType" label="部署类型" width="130"></el-table-column>
            <el-table-column prop="partitionZhname" label="分区名称" width="130"></el-table-column>
            <el-table-column label="创建时间" width="190">
              <template slot-scope="scope">
                <el-tooltip effect="dark" :content="scope.row.updateTime" placement="bottom-start"
                  popper-class="tooltipClass" :disabled="isShowTooltip">
                  <div class="descSpan" style="text-align: left" @mouseover="onMouseOver($event)">
                    {{ scope.row.updateTime }}
                  </div>
                </el-tooltip>
              </template>
            </el-table-column>
            <el-table-column label="状态" width="110">
              <template slot-scope="scope">
                <el-tag type="success" size="medium" v-if="showStatusTag(scope.row) === 2">
                  运行中
                </el-tag>
                <el-tag type="info" size="medium" v-else-if="showStatusTag(scope.row) === 3 ||
                  showStatusTag(scope.row) === 5 ||
                  showStatusTag(scope.row) === 0
                  ">
                  {{ scope.row.yamlStatus }}
                </el-tag>
                <el-tag type="warning" size="medium" v-else-if="showStatusTag(scope.row) === 4">异常
                </el-tag>
                <el-tag size="medium" v-else-if="showStatusTag(scope.row) === 1">更新中
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template slot-scope="scope">
                <el-button type="text" @click="detailCloudNative(scope.row)" style="padding: 0">
                  详情
                </el-button>
                <el-button type="text" @click="viewYamlCloudNative(scope.row)" style="padding: 0">
                  编辑
                </el-button>
                <el-button type="text" @click="rollbackCloudNative(scope.row)" style="padding: 0">
                  回滚
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div style="margin-top: 10px; float: right">
          <el-pagination background layout="total, prev, pager, next, jumper" :total="page.total"
            :page-size="page.pageSize" :page.sync="page" @current-change="changePage" />
        </div>
      </div>
    </div>
    <div v-if="showYamlInfoDialog">
      <show-yaml-info ref="showYamlInfoRef" :tmpCloudNative="tmpCloudNative"></show-yaml-info>
    </div>
    <div v-if="rollbackYamlInfoDialog">
      <el-dialog title="回滚" :visible.sync="rollbackYamlInfoDialog" width="750px">
        <!--        :before-close="handleClose(done)"-->
        <el-form :model="rollbackModelInfo" :rules="rules" ref="rollbackRuleForm" label-width="100px"
          class="demo-ruleForm">
          <!--          <div style="display: flex; justify-content: center">-->
          <el-form-item label="服务名称">
            <div style="width: 95%">
              <el-input v-model="rollbackModelInfo.name" disabled style="width: 100%"></el-input>
            </div>
          </el-form-item>
          <!--          </div>-->
          <!--          <div style="display: flex; justify-content: center">-->
          <el-form-item label="目标版本" prop="version">
            <div style="width: 95%">
              <el-select v-model="rollbackModelInfo.version" placeholder="请选择目标版本" style="width: 100%"
                @change="selectRollbackVersion" @visible-change="handleDropdownVisibilityChange">
                <template v-if="versionList.length">
                  <el-option v-for="item in versionList" :key="item" :label="item" :value="item">
                  </el-option>
                </template>
                <template v-else>
                  <el-option disabled label="当前为最新版本" value="current-latest"></el-option>
                </template>
              </el-select>
            </div>
          </el-form-item>
          <!--          </div>-->
          <el-form-item>
            <div style="height: 35vh; overflow-y: scroll; width: 95%" v-show="yamlValue !== ''">
              <codemirror v-model="yamlValue" :options="cmOptions" />
            </div>
          </el-form-item>
          <el-form-item>
            <div style="display: flex; justify-content: right; width: 95%">
              <el-button type="primary" @click="submitRollback" class="el-button-primary-style"
                :disabled="rollbackModelInfo.version === 'current-latest'">
                回滚
              </el-button>
              <el-button type="primary" class="el-button-primary-style" @click="closeRollbackDialog">
                取消
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </el-dialog>
    </div>
    <div v-if="detailYamlInfoDialog">
      <detail-yaml-info ref="detailYamlInfoRef" :tmpCloudNative="tmpCloudNative"></detail-yaml-info>
    </div>
  </div>
</template>

<script>
import ShowYamlInfo from "@/views/ApplicationManage/CloudNative/ShowYamlInfo.vue";
import { codemirror } from "vue-codemirror";
import "codemirror/lib/codemirror.css";
import "codemirror/mode/yaml/yaml.js";
import DetailYamlInfo from "@/views/ApplicationManage/CloudNative/DetailYamlInfo.vue";
import { getTenantId } from "@/utils/tenantId";

export default {
  name: "CloudNativeManage",
  components: { DetailYamlInfo, ShowYamlInfo, codemirror },
  data() {
    return {
      searchInput: "",
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      tmpPage: {
        pageSize: 10,
        pageNum: 1,
        filterKey: "",
        tenantId: "",
      },
      isShowTooltip: false,
      tableData: [],
      timer: 0,
      showYamlInfoDialog: false,
      tmpCloudNative: "",
      rollbackYamlInfoDialog: false,
      receivedCode: null,
      rollbackModelInfo: {
        id: "",
        name: "",
        version: "",
      },
      rules: {
        version: [
          { required: true, message: "请选择活动区域", trigger: "change" },
        ],
      },
      versionList: [],
      yamlValue: "",
      cmOptions: {
        mode: "yaml", // 使用YAML模式
        theme: "default", // 使用默认主题
        lineNumbers: true, // 显示行号
        line: true, // 显示行高亮
        styleActiveLine: true, // 高亮当前行
        matchBrackets: true, // 括号匹配高亮
        autoCloseBrackets: true, // 自动闭合括号
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"], // 显示行号和折叠标记
        foldGutter: true, // 启用折叠功能
        readOnly: true,
      },
      detailYamlInfoDialog: false,
      selectRowList: [],
    };
  },
  methods: {
    // 监听下拉框是否打开
    handleDropdownVisibilityChange(visible) {
      if (visible && this.versionList.length === 0) {
        // 如果 versionList 为空，并且下拉框被打开，设置选择框的值为 "current-latest"
        this.rollbackModelInfo.version = 'current-latest';
      }
    },
    onMouseOver(event) {
      const ev = event.target;
      const evWeight = ev.scrollWidth;
      const contentWidth = ev.clientWidth;
      if (evWeight > contentWidth) {
        this.isShowTooltip = false;
      } else {
        this.isShowTooltip = true;
      }
    },
    tableSelectionChange(rows) {
      this.selectRowList = rows;
    },
    getAllCloudNativeServiceList() {
      setTimeout(() => {
        this.tmpPage.tenantId = getTenantId();
        if (this.tmpPage.tenantId === undefined) {
          this.$router.push("/");
          this.$message.warning("数据出现问题，请稍后再试");
        } else {
          this.$appManageApi.pageCloudYaml(this.tmpPage).then((res) => {
            if (res && res.code === 200) {
              this.tableData = res.data.records;
              console.log("tableData", this.tableData);
              this.page.total = res.data.total;
              this.getCurrentPageDeployStatus();
            }
          });
        }
      }, 500);
    },
    handleCommand(command, row) {
      this.$refs.multipleTable.clearSelection();
      if (command === "detail") {
        this.detailCloudNative(row.id);
        // } else if (command === "start") {
        //   this.startCloudNative(row.id);
        // } else if (command === "stop") {
        //   this.stopCloudNative(row.id);
      } else if (command === "viewYaml") {
        this.viewYamlCloudNative(row);
      } else if (command === "rollback") {
        this.rollbackCloudNative(row);
        // } else if (command === "delete") {
        //   this.deleteCloudNative(row.id);
      }
    },
    startCloudNative() {
      if (this.selectRowList.length === 0) {
        this.$message.warning("请选择数据之后执行操作");
        // this.$message.error("请选择需要操作的数据");
        return;
      }

      let idList = [];
      for (let i = 0; i < this.selectRowList.length; i++) {
        const row = this.selectRowList[i];
        // 如果类型为cronjob或者job类型，则不允许启动
        if (row.yamlDeployType === "CronJob" || row.yamlDeployType === "Job") {
          this.$message.error("cronjob或者job类型不允许启动，只做删除处理！");
          return;
        }
        if (
          this.showStatusTag(row) === 2 ||
          this.showStatusTag(row) === 4 ||
          this.showStatusTag(row) === 1
        ) {
          this.$message.error(`请先停止 "${row.yamlDeployName}"`);
          return;
        } else {
          idList.push(row.id);
        }
      }
      this.$appManageApi.startCloudYaml(idList).then((res) => {
        if (res && res.code === 200) {
          this.$message.success(res.data);
          this.$refs.multipleTable.clearSelection();
          this.getAllCloudNativeServiceList();
        }
      });
    },
    stopCloudNative() {
      if (this.selectRowList.length === 0) {
        this.$message.warning("请选择数据之后执行操作");
        // this.$message.error("请选择需要操作的数据");
        return;
      }
      let idList = [];
      for (let i = 0; i < this.selectRowList.length; i++) {
        const row = this.selectRowList[i];
        // 如果类型为cronjob或者job类型，则不允许停止
        if (row.yamlDeployType === "CronJob" || row.yamlDeployType === "Job") {
          this.$message.error("cronjob或者job类型不允许停止，只做删除处理！");
          return;
        }
        if (
          this.showStatusTag(row) === 0 ||
          this.showStatusTag(row) === 5 ||
          this.showStatusTag(row) === 3
        ) {
          this.$message.error(`请先启动 "${row.yamlDeployName}"`);
          return;
        } else {
          idList.push(row.id);
        }
      }
      this.$appManageApi.stopCloudYaml(idList).then((res) => {
        if (res && res.code === 200) {
          this.$message.success(res.data);
          this.getAllCloudNativeServiceList();
          this.$refs.multipleTable.clearSelection();
        }
      });
    },
    viewYamlCloudNative(row) {
      this.$refs.multipleTable.clearSelection();
      this.showYamlInfoDialog = true;
      this.tmpCloudNative = row;
      this.$nextTick(() => {
        if (this.$refs.showYamlInfoRef !== undefined) {
          this.$refs.showYamlInfoRef.dialogVisible = true;
          this.$refs.showYamlInfoRef.$on(
            "closeYamlCloudNativeDialog",
            this.closeYamlCloudNativeDialog
          );
        }
      });
    },
    closeYamlCloudNativeDialog() {
      this.showYamlInfoDialog = false;
      this.$refs.showYamlInfoRef.$off("closeYamlCloudNativeDialog");
    },
    deleteCloudNative() {
      console.log("selectRowList", this.selectRowList);
      if (this.selectRowList.length === 0) {
        this.$message.warning("请选择数据之后执行操作");
        // this.$message.error("请选择需要操作的数据");
        return;
      }
      let idList = [];
      for (let i = 0; i < this.selectRowList.length; i++) {
        const row = this.selectRowList[i];
        // 如果是CronJob或者Job则直接进行删除
        if (
          row.yamlDeployType === "CronJob" ||
          row.yamlDeployType === "Job"
        ) {
          idList.push(row.id);
        } else {
          if (
            this.showStatusTag(row) === 2 ||
            this.showStatusTag(row) === 4 ||
            this.showStatusTag(row) === 1
          ) {
            this.$message.error(`请先停止 "${row.yamlDeployName}"`);
            return;
          } else {
            idList.push(row.id);
          }
        }
      }
      this.$appManageApi.deleteCloudYaml(idList).then((res) => {
        if (res && res.code === 200) {
          this.$message.success(res.data);
          this.getAllCloudNativeServiceList();
          this.$refs.multipleTable.clearSelection();
        }
      });
    },
    detailCloudNative(row) {
      this.$refs.multipleTable.clearSelection();
      this.detailYamlInfoDialog = true;
      this.tmpCloudNative = row;
      this.$nextTick(() => {
        if (this.$refs.detailYamlInfoRef !== undefined) {
          this.$refs.detailYamlInfoRef.dialogVisible = true;
          this.$refs.detailYamlInfoRef.$on(
            "closeDetailCloudNative",
            this.closeDetailCloudNative
          );
        }
      });
    },
    closeDetailCloudNative() {
      this.detailYamlInfoDialog = false;
      this.$refs.detailYamlInfoRef.$off("closeDetailCloudNative");
    },
    rollbackCloudNative(row) {
      this.$refs.multipleTable.clearSelection();
      this.rollbackYamlInfoDialog = true;
      this.rollbackModelInfo.id = row.id;
      this.rollbackModelInfo.name = row.yamlName;
      this.$appManageApi.versionCloudYamlInstance(row.id).then((res) => {
        if (res && res.code === 200) {
          this.versionList = res.data;
        }
      });
    },
    filterServiceInstanceList() {
      this.tmpPage.filterKey = this.searchInput;
      this.tmpPage.pageNum = 1;
      this.tmpPage.pageSize = 10;
      this.getAllCloudNativeServiceList();
    },
    changePage(currentPage) {
      this.page.currentPage = currentPage;
      this.tmpPage.pageNum = currentPage;
      this.getAllCloudNativeServiceList();
    },
    showStatusTag(row) {
      let tmpStatus = 0;
      switch (row.yamlStatus) {
        case "未部署":
          tmpStatus = 0;
          break;
        case "更新中":
          tmpStatus = 1;
          break;
        case "运行中":
          tmpStatus = 2;
          break;
        case "已停止":
          tmpStatus = 3;
          break;
        case "异常":
          tmpStatus = 4;
          break;
        default:
          tmpStatus = 5;
      }
      return tmpStatus;
    },
    getCurrentPageDeployStatus() {
      let deployIds = [];
      this.tableData.forEach((ele) => {
        deployIds.push(ele.id);
      });
      this.$appManageApi
        .statusCloudYaml(deployIds)
        .then((res) => {
          if (res && res.code === 200) {
            this.tableData.forEach((ele) => {
              let deployStatusEle = res.data.filter(
                (element) => ele.id === element.id
              )[0];
              let tmpStatus = "";
              switch (deployStatusEle.status) {
                case "NONE":
                  tmpStatus = "未部署";
                  break;
                case "UPDATING":
                  tmpStatus = "更新中";
                  break;
                case "RUNNING":
                  tmpStatus = "运行中";
                  break;
                case "STOPPED":
                  tmpStatus = "已停止";
                  break;
                case "ERROR":
                  tmpStatus = "异常";
                  break;
                case "SUCCEEDED":
                  tmpStatus = "成功执行";
                  break;
                default:
                  tmpStatus = "未知";
              }
              ele.yamlStatus = tmpStatus;
            });
          } else {
            clearInterval(this.timer);
          }
        })
        .catch((error) => {
          this.$message.error(error.message);
        });
    },
    submitRollback() {
      this.$refs.rollbackRuleForm.validate(async (valid) => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "Loading",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          await this.$appManageApi
            .rollbackCloudYaml(this.rollbackModelInfo)
            .then((res) => {
              if (res && res.code === 200) {
                this.$message.success(res.data);
                this.closeRollbackDialog();
                loading.close();
              }
            });
          loading.close();
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    closeRollbackDialog() {
      this.rollbackYamlInfoDialog = false;
      this.rollbackModelInfo = {
        id: "",
        name: "",
        version: "",
      };
      this.versionList = [];
      this.yamlValue = "";
    },
    selectRollbackVersion() {
      this.yamlValue = "";
      this.$appManageApi
        .rollbackCloudYamlDetail(this.rollbackModelInfo)
        .then((res) => {
          if (res && res.code === 200) {
            this.yamlValue = res.data;
          }
        });
    },
  },
  mounted() {
    this.getAllCloudNativeServiceList();
    this.timer = setInterval(() => {
      this.getCurrentPageDeployStatus();
    }, 5000);
  },
  // created() {
  //   this.receivedCode = this.$route.query.code;
  //   if (this.receivedCode) {
  //     this.startCloudNative(this.receivedCode);
  //   }
  // },
  beforeDestroy() {
    clearInterval(this.timer);
  },
};
</script>

<style scoped>
::v-deep .el-pagination.is-background .el-pager li:not(.disabled).active {
  background-color: #304156;
}
</style>
